package com.easyliving.app.lib.net;

import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.easyliving.app.lib.utils.Logger;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import kotlin.jvm.Throws;
import retrofit2.Retrofit;

/**
 * Model层的网络请求Retrofit封装
 * 可以初始化header或者调用builder去动态添加header，其他的在RetrofitFactory中封装了，也可以拿过来动态加载。
 *
 * @author chiboo
 */
public class RemoteLoader {
    private static final Logger logger = Logger.getLogger();
    private static final String TOKEN_HEADER = "Bearer ";
    private static Map<String, String> defaultHeaders;
    private volatile static RemoteLoader remoteLoader;
    private static String mToken;
    private static String mBaseUrl;

    private RemoteLoader() {
    }

    public static RemoteLoader getDefaultLoader() {
        if (remoteLoader == null) {
            synchronized (RemoteLoader.class) {
                if (remoteLoader == null) {
                    remoteLoader = new Builder().build();
                }
            }
        }
        return remoteLoader;
    }

    public static void init(String token, @NonNull String baseUrl) {
        if (!TextUtils.isEmpty(token)) {
            defaultHeaders = new HashMap<>();
            mToken = TOKEN_HEADER + token;
            defaultHeaders.put("Authorization", mToken);
        }
        mBaseUrl = baseUrl;
    }

    public static void init(@NonNull String baseUrl) {
        mBaseUrl = baseUrl;
    }

    /**
     * 设置或更新token
     */
    public static void updateToken(String token) {
        mToken = TOKEN_HEADER + token;
        if (defaultHeaders == null) {
            defaultHeaders = new HashMap<>();
        }
        defaultHeaders.put("Authorization", mToken);
        if (remoteLoader != null) {
            remoteLoader = new Builder().build();
        }
    }

    public static void initHeader(Map<String, String> headers) {
        if (headers != null) {
            defaultHeaders = new HashMap<>();
            defaultHeaders.putAll(headers);
            // 重新设定header
            if (remoteLoader != null) {
                remoteLoader = new Builder().build();
            }
        }
    }


    /**
     * 兼容多个Service类，类型自定义
     *
     * @param service
     * @param <T>
     * @return
     */
    public <T> T loadService(Class<T> service) {
        Retrofit retrofit = null;
        try {
            retrofit = RetrofitFactory.getRetrofit();
        } catch (Exception e) {
            throw new UnsupportedOperationException("Please init RemoteLoader first!");
        }
        return retrofit.create(service);
    }

    public static final class Builder {
        private Map<String, String> headers;
        private String baseUrl;

        private Retrofit buildRetrofit() throws Exception {
            if (headers == null && defaultHeaders != null) {
                headers = defaultHeaders;
            }
            if (baseUrl == null && mBaseUrl != null) {
                baseUrl = mBaseUrl;
            }
            RetrofitFactory.init(baseUrl, headers);
            return RetrofitFactory.getRetrofit();
        }

        public Builder addHeader(Map<String, String> headerMap) {
            this.headers = headerMap;
            return this;
        }

        public Builder addBaseUrl(String baseUrl) {
            this.baseUrl = baseUrl;
            return this;
        }

        public RemoteLoader build() {
            try {
                buildRetrofit();
            } catch (Exception e) {
                throw new UnsupportedOperationException("Please init baseUrl first!");
            }
            return new RemoteLoader();
        }
    }
}
